package fi.jamk.ourcookingapp.adapter;

import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import fi.jamk.ourcookingapp.R;
import fi.jamk.ourcookingapp.activity.AppActivity;
import fi.jamk.ourcookingapp.backend.architecture.manager.ReceiptManager;
import fi.jamk.ourcookingapp.backend.exceptions.EmptySearchException;
import fi.jamk.ourcookingapp.backend.exceptions.NoReceiptException;
import fi.jamk.ourcookingapp.backend.model.User;

/**
 * Adapter for showing the friends list
 * @author Marius
 */
public class MyFriendAdapter extends ArrayAdapter<User> {

	private Context context;
	
	private int resource;
	
	private List<User> lstUser;

	public MyFriendAdapter(Context context, int resource, List<User> user) {
		super(context, resource, user);
		this.context = context;
		this.resource = resource;
		this.lstUser = user;
	}
	
	@SuppressLint("ViewHolder")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View rowView = inflater.inflate(resource, parent, false);
		User user = lstUser.get(position);
		// user name
		TextView txtFriendName = (TextView) rowView.findViewById(R.id.text);
		txtFriendName.setText(user.getLoginName());
		
		try {
			AppActivity.facade.setFilter(ReceiptManager.USER_ID, user.getID());
			TextView txtReceiptsAdded = (TextView) rowView.findViewById(R.id.receiptsAdded);
			txtReceiptsAdded.setText(AppActivity.facade.filter(true).size() + " " + AppActivity.facade.getResources().getString(R.string.receiptsAdded));
		} catch (EmptySearchException | NoReceiptException
				| InterruptedException | ExecutionException | JSONException e) {
		}
		
		return rowView;
	}
	
}
